package portal.monitor.controller;

import beans.HttpResultList;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import portal.monitor.dao.MonitorRelated;
import portal.monitor.dao.service.MonitorRelatedService;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class MonitorRelatedServlet extends HttpServlet {
    @Autowired
    MonitorRelatedService monitorRelatedService;
    private HttpResultList result;

    @RequestMapping(value = "/MonitorRelatedServlet", method = RequestMethod.POST)
    public void RelatedService(HttpServletRequest request, HttpServletResponse response) throws IOException {
        result = new HttpResultList();
        String operateType = request.getParameter("operateType");
        try {
            switch (operateType) {
                case "showAll":
                    showAll();
                    break;
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
            result.setResult(false);
            result.setMessage("POST参数错误");
            response.getWriter().print(JSONObject.fromObject(result).toString());
        } catch (NumberFormatException e) {
            e.printStackTrace();
            result.setResult(false);
            result.setMessage("POST数字错误");
        }
        response.getWriter().print(JSONObject.fromObject(result).toString());
    }

    private void showAll() {
        List<MonitorRelated> relatedList = monitorRelatedService.selectAll();
        List<List<Integer>> objects = new ArrayList<>();
        if(relatedList.size()>0){
            int hostId = -1;
            for(MonitorRelated monitorRelated:relatedList){
                if(monitorRelated.getHostId()!=hostId){
                    List<Integer> list = new ArrayList<>();
                    list.add(monitorRelated.getHostId());
                    list.add(monitorRelated.getHostGroupId());
                    objects.add(list);
                }else {
                    objects.get(objects.size() - 1).add(monitorRelated.getHostGroupId());
                }
            }
            result.setResult(objects.size() > 0);
            result.setDatas(new ArrayList<Object>(objects));
        }else {
            result.setResult(false);
        }

    }

}
